#include "oesupermanagersqldatabase.h"

#include <QFile>
#include <QDir>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>

#include "oeloginsqldatabase.h"
extern OELoginSqlDatabase g_db;

QString OESuperManagerSqlDatabase::dbFileName_;
OESuperManagerSqlDatabase::OESuperManagerSqlDatabase(QObject *parent)
    : QObject(parent)
{

}

int OESuperManagerSqlDatabase::checkDB()
{
    QSqlDatabase db;
    int ret = openDB(dbFileName_, db);
    if (0 != ret)
        return ret;

    if (!db.isOpen()) {
        qWarning() << "login failed, because db not open!";
        return 110;
    }
    const QString& sql = QString("SELECT name FROM audit_account;");

    QSqlQuery query(db);

    if (!query.exec(sql)) {
        qWarning("db structure exceptions");
        return -1;
    }

    int i = 0;
    while(query.next())
        ++i;

    if (i < 2) {
        return -1;
    }

    return 0;
}

int OESuperManagerSqlDatabase::registerDB(const QString &_dbFileName,
                                          const QString &_sqlRes)
{

    QSqlDatabase sql_database;
    int ret = openDB(_dbFileName, sql_database);
    if (0 != ret)
        return ret;


    // 获得初始化的Sql语句
    QFile file(_sqlRes);

    QSqlQuery query(sql_database);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qFatal("Can't open the file!");
        return 4;
    }
    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        if (!query.exec(line)) {
            qWarning() << query.lastError();
            continue;
        }
    }
    file.close();
    dbFileName_ = _dbFileName;

    return 0;
}

int OESuperManagerSqlDatabase::registerUser(const QString &_user,
                                            const QString &_pswd,
                                            const QString &_name,
                                            const QString &_issue1,
                                            const QString &_answer1,
                                            const QString &_issue2,
                                            const QString &_answer2)
{

    QSqlDatabase sql_database;
    int ret = openDB(dbFileName_, sql_database);
    if (0 != ret)
        return ret;

    QSqlQuery query(sql_database);

//    QString md_pswd = encryptionPswd(_pswd);

    if (!query.exec(QString("INSERT INTO audit_account (name,user,pswd,issue1,answer1,issue2,answer2)\
                                VALUES ('%1', '%2', '%3','%4','%5','%6','%7');")
                     .arg(_name).arg(_user).arg(_pswd).arg(_issue1).arg(_answer1).arg(_issue2).arg(_answer2))) {
        qInfo("register db failed.");
        qWarning() << query.lastError();
        return -1;
    }
    return 0;
}

int OESuperManagerSqlDatabase::getAccountInfo(const QString &_user, QString &_username,
                           QString &_issue1, QString &_issue2)
{
    QSqlDatabase sql_database;
    int ret = openDB(dbFileName_, sql_database);
    if (0 != ret)
        return ret;

    QSqlQuery query(sql_database);

    if (!query.exec(QString("SELECT name, issue1, issue2 FROM audit_account WHERE user = '%1'")
                     .arg(_user))) {
        qInfo("register db failed.");
        qWarning() << query.lastError();
        return -1;
    }

    while(query.next()) {
        _username = query.value(0).toString();
        _issue1 = query.value(1).toString();
        _issue2 = query.value(2).toString();
        if (query.next())
            qCritical() << "login appears with same account.";
    }
    return 0;
}

int OESuperManagerSqlDatabase::checkAccountInfo(const QString &_user,
                                                const QString &_issue1,
                                                const QString &_answer1,
                                                const QString &_issue2,
                                                const QString &_answer2) {

    QSqlDatabase sql_database;
    int ret = openDB(dbFileName_, sql_database);
    if (0 != ret)
        return ret;

    QSqlQuery query(sql_database);

    QString sql = QString("SELECT user FROM audit_account WHERE user = '%1' AND "\
                          " issue1 = '%2' AND answer1 = '%3' AND "\
                          " issue2 = '%4' AND answer2 = '%5';")
                   .arg(_user).arg(_issue1).arg(_answer1).arg(_issue2).arg(_answer2);
    qDebug() <<sql;
    if (!query.exec(sql)) {
        qInfo("check account info failed.");
        qWarning() << query.lastError();
        return -1;
    }

    QString u;
    while(query.next()) {
        u = query.value(0).toString();
    }
    if (u.isEmpty())
        return -1;
    return 0;
}

int OESuperManagerSqlDatabase::modifyName(const QString &_user,
                                          const QString &_pswd,
                                          const QString &_newName)
{
    QSqlDatabase sql_database;
    int ret = openDB(dbFileName_, sql_database);
    if (0 != ret)
        return ret;
#if 0 // 需要验证用户账号密码
    const QString& sql = QString(" UPDATE audit_account SET "\
                                 " name = %1 "\
                                 " WHERE uesr = '%2' AND pswd = '%3'; ")
                            .arg(_newName).arg(_user).arg(_pswd);
#else // 不验证用户密码
    Q_UNUSED(_pswd);
    const QString& sql = QString(" UPDATE audit_account SET "\
                                 " name = '%1' "\
                                 " WHERE user = '%2'; ")
                            .arg(_newName).arg(_user);
#endif

    QSqlQuery query(sql_database);
    if (!query.exec(sql)) {
        qInfo("modify name failed.");
        qWarning() << query.lastError();
        return -1;
    }
    g_db.info_.name = _newName;

    return ret;
}

int OESuperManagerSqlDatabase::modifyPswd(const QString &_user,
                                          const QString &_pswd,
                                          const QString &_newPswd)
{
    QSqlDatabase sql_database;
    int ret = openDB(dbFileName_, sql_database);
    if (0 != ret)
        return ret;
#if 0 // 用旧密码改新密码
    const QString& sql = QString(" UPDATE audit_account SET "\
                                 " pswd = %1 "\
                                 " WHERE user = '%2' AND pswd = '%3'; ")
                            .arg(_newPswd).arg(_user).arg(_pswd);
#else // 不需要旧密码做验证
    Q_UNUSED(_pswd);
    const QString& sql = QString(" UPDATE audit_account SET "\
                                 " pswd = %1 "\
                                 " WHERE user = '%2'; ")
                            .arg(_newPswd).arg(_user);
#endif
    //
    QSqlQuery query(sql_database);
    if (!query.exec(sql)) {
        qInfo("modify pswd failed.");
        qWarning() << query.lastError();
        return -1;
    }

    return ret;
}

int OESuperManagerSqlDatabase::openDB(const QString &_dbName,
                                      QSqlDatabase &_db)
{
    int ret = 0;

    if (_db.isOpen()) {
        _db.close();
    }
    if (QSqlDatabase::contains(_dbName)) {
        _db = QSqlDatabase::database(_dbName);
    }
    else {
        _db = QSqlDatabase::addDatabase("QSQLITE",_dbName);
        _db.setDatabaseName(_dbName);
    }

    if (!_db.open()) {
        qWarning() << "Error: Failed to connect database." << _db.lastError();
        ret = 4;
    }

    return ret;

}

int OESuperManagerSqlDatabase::checkPswd(const QString &_user,
                            const QString &_pswd)
{
    QSqlDatabase db;
    int ret = openDB(dbFileName_, db);
    if (0 != ret)
        return ret;

    if (!db.isOpen()) {
        qWarning() << "login failed, because db not open!";
        return 110;
    }
    const QString& sql = QString("SELECT name FROM audit_account "\
                                 "WHERE user = '%1' AND "\
                                 "pswd = '%2';")
                        .arg(_user).arg(_pswd);
    QSqlQuery query(db);

    if (!query.exec(sql)) {
        qInfo() << "exec(sql), password error.";
        return -1;
    }
    QString name;
    while(query.next()) {
        name = query.value(0).toString();
        if (query.next())
            qCritical() << "login appears with same account.";
    }
    if (name.isEmpty()) {
        qDebug() << "password error.";
        return -1;
    }

    return 0;

}

bool OESuperManagerSqlDatabase::isExist(void) {
    QFile file(dbPath());
    if(file.exists()) {
        return true;
    }
    return false;
}

QString OESuperManagerSqlDatabase::dbPath()
{
    QString path = QDir::currentPath();
    path += "/";
    path += dbFileName_;
    return path;
}
